package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import logic.ShoppingKart;

public class JDBCPurchaseDAO implements IPurchaseDAO{
	
	private Connection c;
	IProductDAO pdao;
	IDestinationDAO ddao;
	String idDest;
	
	public JDBCPurchaseDAO() {
	       c = ConnectionManager.getInstance().checkOut();
	       pdao = new JDBCProductDAO();
	       ddao = new JDBCDestinationDAO();
	}
	
	protected void finalize() {
	       ConnectionManager.getInstance().checkIn(c);
	}

	public void insertPurchase(ShoppingKart s) {
		
		//modified field sell in products table
		pdao.deleteProductsFromCatalogue(c, s.getProductList());
		

		for(int i = 0; i < s.getProductList().size(); i++){
			
			//put idBuyer in all products from the purchase
			pdao.insertBuyerInProduct(c, s.getProductList().get(i), s.getIdUser());
			//first, we need to select the destinations
			idDest = pdao.selectDestinationFromProduct(c, s.getProductList().get(i));
			if(idDest == null || idDest.length() <= 0){
				idDest = s.getIdDestination();
				if(idDest.equals("noDest")){
					idDest = ddao.selectRandomDest();
				}
				pdao.insertDestinationInProduct(c, s.getProductList().get(i), idDest);
			}
			//put profits in destinations table
			float profits = ddao.selectProfitsFromDest(c, idDest);
			profits += pdao.selectPrice(c, s.getProductList().get(i));
			ddao.addProfitsInDestination(c, idDest, profits);
		}
		
		PreparedStatement stmt = null;
		String sql = "INSERT INTO purchasehistory ( id, iduser, totalproducts, totalprice) VALUES (?, ?, ?, ?)";
        try {
            stmt = c.prepareStatement(sql);
            stmt.setString(1, s.getId());
            stmt.setString(2, s.getIdUser());
            stmt.setLong(3, s.getTotalProducts());
            stmt.setFloat(4, s.getTotalPrice());
            stmt.executeUpdate();

	        } catch (SQLException e) {
	            System.out.println("Message: insertPurchase: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
	    }
	}
	
	
	//Tirso
	public ShoppingKart selectPurchase(String idShoppingKart) {
		PreparedStatement stmt = null;
		String sql = "SELECT * FROM purchasehistory WHERE id = ?";
		ShoppingKart s = new ShoppingKart();
		ResultSet result = null;
		try{
			stmt = c.prepareStatement(sql);
			stmt.setString(1, idShoppingKart);
			result = stmt.executeQuery();
			result.next();
			s.setId(idShoppingKart);
			s.setIdDestination(result.getString("destination"));
			s.setDate(result.getDate("date"));
			s.setIdUser(result.getString("user"));
			s.setTotalPrice(result.getFloat("price"));
			s.setTotalProducts(result.getInt("totalproducts"));
			//falta lista productos y ver idShoppingKart
			
		}catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
        	}
        }
		return s;
	}

	public void deletePurchase(String idShoppingKart) {
		PreparedStatement stmt = null;
		String sql = "DELETE * FROM purchasehistory WHERE (id = ?)";
        try {
            stmt = c.prepareStatement(sql);
            stmt.setString(1, idShoppingKart);
            stmt.executeUpdate();

	        } catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
	    }
	}
		
}
	

